//
//  AppDelegate.m
//  TalkWrench
//
//  Created by Nguyen Minh Khoai on 1/29/13.
//  Copyright (c) 2013 Nguyen Minh Khoai. All rights reserved.
//

#import "AppDelegate.h"
//#import <Crashlytics/Crashlytics.h>
#import "HomeViewController.h"
#import "LeftMenuViewController.h"
#import "RightMenuViewController.h"

@interface AppDelegate()
@property (nonatomic, strong)   NSDictionary *remoteNotification;
@end

@implementation AppDelegate
@synthesize fbService;
@synthesize hasNetwork;
@synthesize dataCenter;
@synthesize networkMonitor;

- (void)dealloc {
    NotifUnregAll(self);
    [networkMonitor stopNotifier];
}


#pragma mark - Accessors

- (CCCoreDataHelper *)dataHelper {
    if (!_dataHelper) {
        _dataHelper  = [CCCoreDataHelper sharedModel:self];
    }
    return _dataHelper;
}

- (UIViewController *)mainViewController {
    if (!_mainViewController) {
        _mainViewController = [[IBHelper sharedUIHelper] loadViewController:@"MainVC" inStory:@"MainController"];
    }
    return _mainViewController;
}

#pragma mark - Support Methods

- (BOOL)hasNetwork {
    NetworkStatus status = networkMonitor.currentReachabilityStatus;
    self.hasNetwork = (status != NotReachable);
    return hasNetwork;
}

- (void)handleChangeNetworkStatus:(NSNotification *)notification {
    NetworkStatus status = networkMonitor.currentReachabilityStatus;
    BOOL reachable = (status != NotReachable);
    if(reachable) {
        
    }
}

- (void)didFinishedAnimation:(SplashScreenView *)view {
    if([SplashScreenView sharedSplashScreen].superview) {
        [[SplashScreenView sharedSplashScreen] removeFromSuperview];
    }
    self.window.rootViewController = self.mainViewController;
}

- (void)redirectConsoleLogToDocumentFolder {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *logPath = [documentsDirectory stringByAppendingPathComponent:@"DealHits.log"];
    
    /* remove old file */
    [[NSFileManager defaultManager] removeItemAtPath:logPath error:nil];
    
    /* redirect to file */
    freopen([logPath fileSystemRepresentation],"a+",stderr);
}

#pragma mark - UIApplicationDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    /* write log to file */
   // [self redirectConsoleLogToDocumentFolder];
    
    /* Crashlytics */
    //    [Crashlytics startWithAPIKey:@"8522b7866882fd255a012dd805bed600da6341d4"];
    
    /* skip to backup to iCloud */
    [[FileHelper sharedManager] preventiCloudAutoBackup];
    
    /* Start tracking service */
    TrackingService *trackingService = [TrackingService sharedTrackingService];
    [trackingService startSession];
    [trackingService trackingLocation];
    
    /* initialize and listen changing network status signal */
    self.networkMonitor = [Reachability reachabilityForInternetConnection];
    [networkMonitor startNotifier];
    
    /* initialize datacenter */
    self.dataCenter = [[DataCenter alloc]init];
    
    /* initialize and listen changing network status signal */
    NotifReg(self, @selector(handleChangeNetworkStatus:), kReachabilityChangedNotification);
    
    /* create FB service */
    [FBProfilePictureView class];
    fbService = [[FacebookSocialService alloc] init];
    
    /* create twitter service */
    _twService = [[TwitterSocialService alloc] init];
    
    /* create linkedIn service */
    _linkedInService = [[LinkedInSocialService alloc] init];
    
    /* open by tapping Push Notification */
    self.remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    
    /* reset badge number */
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    UIImage *imageBar = [NLUtils imageFromColor:UIColorFromRGB(0x1B689F)];
    [[UINavigationBar appearance] setBackgroundImage:imageBar forBarMetrics:UIBarMetricsDefault];
    
    self.window.rootViewController = self.mainViewController;
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    //    [splashView startAnimation];
    
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    //    [self.dataCenter.service stopUpdatingLocation];
    [(MainViewController *)self.mainViewController applicationWillResignActive];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [(MainViewController *)self.mainViewController applicationDidEnterBackground];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [(MainViewController *)self.mainViewController applicationWillEnterForeground];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [fbService handleBecomeActive];
    [(MainViewController *)self.mainViewController applicationDidBecomeActive];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [(MainViewController *)self.mainViewController applicationWillTerminate];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *deviceTokenString = [[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""];
    deviceTokenString = [deviceTokenString stringByReplacingOccurrencesOfString:@">" withString:@""];
    self.deviceToken = deviceTokenString;
    DLog(@"deviceToken: %@", deviceTokenString);
    
    /* if user logged in, update device token */
    [(MainViewController *)self.mainViewController didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    self.remoteNotification = userInfo;
    [(MainViewController *)self.mainViewController didReceiveRemoteNotification:userInfo];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    return [fbService handleOpenURL:url];
}

#pragma mark CoreDataDelegate

- (void)persistentStoreDidChange {
    
}

@end
